package com.google.code.opengw.server.support;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import com.google.code.opengw.server.Constants;
import com.google.code.opengw.server.Server;
import com.google.code.opengw.support.OpenGWException;

public class FileUtils {
	public static File getDirectory(String path) throws OpenGWException{
		File file = new File(path);
		if(!file.exists() || !file.isDirectory())
			throw new OpenGWException(OpenGWException.DIRECTORY_NOT_FOUND, path);
		return file;
	}
	
	public static boolean checkDirectoryExists(String path){
		File file = new File(path);
		if(file.exists() && file.isDirectory())
			return true;
		return false;
	}
	
	public static boolean checkFileExists(String path){
		File file = new File(path);
		if(file.exists() && file.isFile())
			return true;
		return false;
	}
	
	public static boolean createDirectory(String path){
		File file = new File(path);
		return file.mkdir();
	}
	
	public static byte[] readFile(File file) throws IOException{
		FileInputStream inputStream = new FileInputStream(file);
		byte[] data = new byte[inputStream.available()];
		inputStream.read(data);
		inputStream.close();
		return data;
	}
	
	public static byte[] readDataFromInputStream(InputStream inp) throws IOException {
		byte[] buffer = new byte[1024];
		int len;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		;
		while ((len = inp.read(buffer)) >= 0)
			out.write(buffer, 0, len);

		inp.close();
		out.close();
		return out.toByteArray();
	}
	
	// Deletes all files and subdirectories under dir.
	// Returns true if all deletions were successful.
	// If a deletion fails, the method stops attempting to delete and returns
	// false.
	public static boolean deleteDir(File dir) {
		if (dir != null && dir.exists() && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
			return dir.delete();
		} else if(dir != null && dir.exists()){
			return dir.delete();
		}
		return false;
	}
}
